<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="84px">
      <el-form-item label="授权码" prop="key">
        <el-input v-model.trim="queryParams.key" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="token" prop="token">
        <el-input v-model.trim="queryParams.token" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryParams.date"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="到期时间">
        <el-date-picker
          v-model="queryParams.expireTime"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="使用账号池" prop="islink">
        <el-radio-group v-model="queryParams.islink">
          <el-radio label="" value="">全部</el-radio>
          <el-radio label="1" value="1">是</el-radio>
          <el-radio label="0" value="0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="ids.length > 0">
        <el-button type="danger" plain icon="Delete" @click="batchDelete">批量删除</el-button>
      </el-col>

      <el-col :span="1.5" v-if="ids.length > 0">
        <el-button type="primary" plain @click="batchUpdate">批量更新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain @click="exportAll">导出筛选数据</el-button>
      </el-col>
      <el-col :span="9">
        <el-alert title="关联账号池数据点击展开可查看频道下所有token快速剩余时间" type="warning" />
      </el-col>
      <right-toolbar :search="false" v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table ref="tableRef" v-loading="loading" row-key="id" lazy :data="list" :load="load" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :align="`center`" />

      <el-table-column label="授权码" prop="key" width="340">
        <template #default="{ row }">
          <span
            @click="checkAccount(row)"
            class="on-default"
            :class="{
              'on-success': row.online === true,
              'on-error': row.online === false,
            }"
            >{{ row.key }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="token" prop="token" width="400">
        <template #default="{ row }">
          <span
            :class="{
              'on-success': row.online === true,
              'on-error': row.online === false,
            }"
            >{{ row.token }}</span
          >
        </template>
      </el-table-column>
      <el-table-column
        label="快速时间剩余"
        prop="fastTimeRemaining"
        width="200"
      >
      </el-table-column>
      <el-table-column label="调用次数" prop="count"> </el-table-column>
      <el-table-column label="快速模式使用次数" prop="fastUseCount" width="200"> </el-table-column>
      <el-table-column label="快速模式总次数" prop="fastMaxCount" width="200"> </el-table-column>
      <el-table-column label="relax模式使用次数" prop="relaxUseCount" width="200"> </el-table-column>
      <el-table-column label="relax模式总次数" prop="relaxMaxCount" width="200"> </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180"> </el-table-column>
      <el-table-column label="到期时间" prop="expireTime" width="180"> </el-table-column>

      <el-table-column label="备注" prop="remark" width="160"> </el-table-column>
      <el-table-column label="菜单id" prop="guildId" width="180"> </el-table-column>
      <el-table-column label="频道id" prop="channelId" width="180"> </el-table-column>
      <el-table-column label="用户名" prop="userName" width="180"> </el-table-column>
      <el-table-column label="操作" :align="`center`" fixed="right" class-name="small-padding fixed-width" width="200">
        <!-- 未结算才能启用 -->
        <template #default="{ row }">
          <template v-if="row.level === 1">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(row)"></el-button>
            </el-tooltip>
            <el-tooltip content="校验账号" placement="top">
              <el-button link type="primary" icon="Service" @click="checkAccount(row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="deleteHandler(row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="row.token && row.source !== 2" content="激活" placement="top">
              <el-button link type="primary" @click="activeHandler(row)">激活</el-button>
            </el-tooltip>
          </template>
          <template v-else-if="!row.expireTime">
            <el-tooltip content="删除账号池账号" placement="top">
              <el-button link type="danger" icon="Delete" @click="deletePool(row)"></el-button>
            </el-tooltip>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total > 0"
      :total="total"
      v-model:page="pagination.current"
      v-model:limit="pagination.size"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="roleRef" :inline="false" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="授权码" prop="key">
          <el-input :disabled="isEdit" v-model.trim="form.key" placeholder="请输入授权码" />
        </el-form-item>

        <el-form-item label="token" prop="token">
          <el-input v-model.trim="form.token" :disabled="form.source === 2" placeholder="请输入token" />
        </el-form-item>

        <!-- <el-form-item label="账号类型" prop="type">
          <el-select v-model="form.type" placeholder="账号类型" clearable style="width: 240px">
            <el-option v-for="dict in MAP.categoryMap" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="服务器id" prop="guildId">
          <el-input v-model.trim="form.guildId" placeholder="请输入服务器id" />
        </el-form-item>
        <el-form-item label="频道id" prop="channelId">
          <el-input v-model.trim="form.channelId" placeholder="请输入频道id" />
        </el-form-item>

        <!-- 套餐框 -->
        <template v-if="!isEdit">
          <el-form-item label="选择套餐" prop="type">
            <el-select v-model="form.meal" @change="mealChangeHandler">
              <el-option v-for="(item, index) in mealList" :key="index" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
        </template>

        <el-form-item label="生成数量" prop="count" v-if="!isEdit">
          <el-input-number v-model="form.count" :min="1" :max="100" :precision="0" />
        </el-form-item>

        <el-form-item label="快速模式限制次数" prop="fastMaxCount">
          <template #label>
            <el-tooltip class="box-item" effect="dark" content="输入-1为无限次数" placement="top">
              <el-button link type="danger">fast限制次数</el-button>
            </el-tooltip>
          </template>
          <el-input-number v-model="form.fastMaxCount" :min="1" :precision="0" />
        </el-form-item>

        <el-form-item label="relax模式限制次数" prop="relaxMaxCount">
          <template #label>
            <el-tooltip class="box-item" effect="dark" content="输入-1为无限次数" placement="top">
              <!-- <span>relax模式限制次数</span> -->
              <el-button link type="danger">relax限制次数</el-button>
            </el-tooltip>
          </template>
          <el-input-number v-model="form.relaxMaxCount" :min="-1" :precision="0" />
        </el-form-item>

        <el-form-item label="到期时间" prop="expireTime">
          <el-date-picker :disabled="!isEdit" v-model="form.expireTime" type="datetime" placeholder="请选择" />
        </el-form-item>

        <el-form-item label="是否关联账号池" prop="islink">
          <!-- <el-date-picker :disabled="!isEdit" v-model="form.expireTime" type="datetime" placeholder="请选择" /> -->
          <el-radio-group v-model="form.islink">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input :rows="3" type="textarea" v-model.trim="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="formLoading">确 定 </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <PanelBatchUpdate @refresh="getList" ref="bactchUpdateInstance"></PanelBatchUpdate>
  </div>
</template>

<script setup name="Index">
import { listApi, createApi, deleteApi, updateApi, listAllApi, getDiscordUser } from "@/api/base/index.js";
import { getPoolAccount, getStoreAccount, removeStoreAccount } from '@/api/pool.js'
import usePagination from "@/hooks/usePagination";
import { deepClone, generateRandomHex } from "@/utils";
import { ElMessage, dayjs } from "element-plus";
import { useRoute } from "vue-router";
import MAP, { getEnumLabel } from "@/enum/index.js";
import PanelBatchUpdate from "./components/update-dialog.vue";
import * as XLSX from "xlsx";
import axios from "axios";
import { getAllMeal } from "@/views/account/helper/meal.js";

// const router = useRouter();,categoryMap
const { proxy } = getCurrentInstance();
const { pagination, total } = usePagination();
const route = useRoute();

const type = route.meta.type || 0;

const list = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const isEdit = computed(() => title.value === "修改");
const bactchUpdateInstance = ref(null);
const mealList = ref([]);
const poolList = ref([])
const tableRef = ref()

const currentParams = computed(() => {
  const obj = deepClone(unref(queryParams.value));
  const [stm, etm] = obj.date || [];
  const [eStm, eEtm] = obj.expireTime || [];
  if (stm) {
    obj.createTimeStart = dayjs(stm).startOf("day").format("YYYY-MM-DD HH:mm:ss");
  }
  if (etm) {
    obj.createTimeEnd = dayjs(etm).endOf("day").format("YYYY-MM-DD HH:mm:ss");
  }
  if (eStm) {
    obj.expireTimeStart = dayjs(eStm).startOf("day").format("YYYY-MM-DD HH:mm:ss");
  }
  if (eEtm) {
    obj.expireTimeEnd = dayjs(eEtm).endOf("day").format("YYYY-MM-DD HH:mm:ss");
  }
  delete obj.date;
  delete obj.expireTime;
  return obj;
});

// 第三方账号hash
const poolHash = computed(() => {
  return poolList.value.reduce((cache, item) => {
    cache[item.userToken] = item
    return cache
  }, {})
})

const data = reactive({
  form: {},
  queryParams: {
    type,
  },
  rules: {
    token: [{ required: true, message: "token不能为空", trigger: "blur" }],
    guildId: [{ required: true, message: "服务器id不能为空", trigger: "blur" }],
    type: [{ required: true, message: "套餐不能为空", trigger: "blur" }],
  },
  formLoading: false,
});

const { queryParams, form, rules, formLoading } = toRefs(data);

// 批量更新操作
const batchUpdate = () => {
  bactchUpdateInstance.value.init(ids.value);
};

// 导出所选条件数据
const exportAll = async () => {
  loading.value = true;
  const response = [];
  try {
    const res = await listAllApi({
      ...currentParams.value,
    });
    response.push(...res.rows);
  } catch (error) {}
  loading.value = false;
  if (response.length === 0) {
    ElMessage.warning("数据为空");
    return;
  }

  const keys = {
    key: "授权码",
    token: "token",
    pCount: "使用次数",
    type: "账号类型",
    createTime: "创建时间",
    channelId: "渠道id",
    guildId: "导航id",
    maxUser: "最多服务器数",
    remark: "备注",
  };
  const keysName = Object.keys(keys);
  const valuesName = keysName.map((key) => keys[key]);
  const data = response.map((item) => {
    return keysName.map((key) => {
      if (key === "type") {
        return getEnumLabel(MAP.categoryMap, item[key]);
      }
      return item[key];
    });
  });
  data.unshift(valuesName);
  // const data = [
  //   ["姓名", "年龄", "城市"],
  //   ["John Doe", 30, "New York"],
  //   ["Jane Doe", 25, "San Francisco"],
  //   ["Bob Smith", 35, "Los Angeles"],
  // ];

  // 创建一个工作簿
  const workbook = XLSX.utils.book_new();

  // 创建一个工作表
  const worksheet = XLSX.utils.aoa_to_sheet(data);

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "数据");

  // 将工作簿转为二进制数据
  XLSX.writeFile(workbook, "用户列表.xlsx");

  // // 创建下载链接
  // const link = document.createElement("a");
  // link.href = window.URL.createObjectURL(excelBlob);
  // link.download = "用户列表.xlsx";

  // // 触发点击链接进行下载
  // link.click();

  // // 释放对象URL，防止内存泄漏
  // window.URL.revokeObjectURL(link.href);
};

// 激活账号
const activeHandler = (row) => {
  proxy.$modal
    .confirm("是否确认激活账号?")
    .then(async function () {
      const discordUser = await getUserByToken(row.token)
      if(discordUser.username) {
        row.userName = discordUser.username
        await updateApi(row);
        // 更新
        getList();
        proxy.$modal.msgSuccess("激活成功");
      } else {
        // proxy.$modal.msgSuccess("激活成功");
        return
      }
    })
    .catch(() => {
    });
}

// 删除操作
const deleteHandler = (row) => {
  proxy.$modal
    .confirm("是否确认删除数据项?")
    .then(function () {
      return deleteApi(row.key);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

// 删除账号池账号
const deletePool = (row) => {
  proxy.$modal
    .confirm("是否确认删除账号池账号?")
    .then(function () {
      return removeStoreAccount({
        guildId: row.guildId,
        channelId: row.channelId,
        token: row.token
      });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

//
const checkAccount = async (row) => {
  loading.value = true;
  try {
    await axios.get(`https://discord.com/api/v9/users/@me/billing/payment-sources`, {
      headers: {
        Authorization: row.token,
      },
    });
    row.online = true;
    proxy.$modal.msgSuccess("token账号有效");
  } catch (error) {
    if (error.response.status === 401) {
      row.online = false;
      ElMessage.error("token账号无效");
    } else {
      ElMessage.error("未知错误");
    }
  }
  loading.value = false;
};

// 批量删除
// 删除操作
const batchDelete = () => {
  proxy.$modal
    .confirm("是否批量删除数据项?请注意，删除之后将无法恢复")
    .then(function () {
      return deleteApi(ids.value.map((v) => v.key).join(","));
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 查询角色列表 */
function getList() {
  loading.value = true;
  listApi({
    ...currentParams.value,
    pageNo: pagination.current,
    pageSize: pagination.size,
  })
    .then((response) => {
      if (tableRef.value) {
        const treeData = tableRef.value.store.states.treeData
        Object.keys(treeData.value).forEach(key => {
          treeData.value[key].expanded = false
          treeData.value[key].loaded = false
        })
      }
      list.value = (response.rows || []).map(d => {
        return {
          ...d,
          level: 1,
          id: d.key,
          hasChildren: !!d.islink && d.channelId
        }
      });
      loading.value = false;
      total.value = response.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 搜索按钮操作 */
function handleQuery() {
  // pagination.current = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.date = "";
  queryParams.value.expireTime = "";
  handleQuery();
}

/** 重置新增的表单以及其他数据  */
function reset() {
  // menuExpand.value = false;
  // menuNodeAll.value = false;
  // deptExpand.value = true;
  // deptNodeAll.value = false;
  proxy.resetForm("roleRef");
  form.value = {};
}

/** 添加角色 */
function handleAdd() {
  reset();
  form.value.key = generateRandomHex()
  form.value.islink = 0;
  form.value.count = 1;
  form.value.type = type || "";
  open.value = true;
  title.value = "添加";
}

/** 修改角色 */
async function handleUpdate(row) {
  reset();
  title.value = "修改";
  form.value = deepClone(unref(row));
  open.value = true;
}

async function getUserByToken (token) {
  return new Promise((resolve, reject) => {
    getDiscordUser(token).then(res => {
      resolve(res.data || {})
    }).catch(() => {
      proxy.$modal.msgError("激活失败");
      resolve({})
    })
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(async (valid) => {
    if (valid) {
      formLoading.value = true;
      if (form.value.token && !form.value.userName && form.value.source !== 2) {
        const discordUser = await getUserByToken(form.value.token)
        form.value.userName = discordUser.username
      }
      try {
        if (title.value === "修改") {
          // 更新
          await updateApi(unref(form.value));
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        } else {
          // 保存
          if (form.value.count > 1) {
            form.value.key = "";
          }
          await createApi(unref(form.value));
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }
      } catch (error) {}
      formLoading.value = false;
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

// 懒加载操作查询当前频道下账号池所有账号的快速信息
async function load(row, treeNode, resolve) {
  const { channelId } = row
  if(!poolList.value.length) {
    await getPoolAccount({
      current: 1,
      pageNumber: 0,
      pageSize: 30000 // 尽量获取所有数据，后续自定义接口通过token去过滤
    },
    {
      'content-type': 'application/json',
      'mj-api-secret': 'dffdf454l45s93ljs22sddsya'
    }).then((response) => {
      poolList.value = response.data.content
    })
  }
  if(!channelId) {
    resolve([])
    return
  }
  getStoreAccount({
    channelId
  }).then((data) => {
    // 当前账号信息页一起展示
    const resData = ([{ ...row, level: '', id: `pool-${row.key}`, hasChildren: false }].concat(data.filter(d => d.token !== row.token))).map(d => {
      const pool = poolHash.value[d.token] || {}
      return {
        ...pool,
        ...d,
        id: `pool-${pool.key}`
      }
    })
    resolve(resData)
  }).catch(() => {
    resolve([])
  })
}

/**
 *
 */
const mealChangeHandler = (e) => {
  const item = mealList.value.find((v) => v.id === e);
  if (!item) return;
  form.value.fastMaxCount = item.fast;
  form.value.relaxMaxCount = item.relax;
  form.value.expireTime = item.expireTime;
  form.value.type = item.type;
};

getList();

watch(
  () => open.value,
  (val) => {
    if (val) {
      mealList.value = getAllMeal().map((v, i) => {
        return {
          ...v,
          id: i,
        };
      });
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.on-default {
  color: var(--el-color-primary);
}

.on-success {
  color: var(--el-color-success);
}

.on-error {
  color: var(--el-color-error);
}
</style>
